<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline" v-hasPermi="['sa:schedule:query']">
      <el-form-item label="名称" prop="name">
        <el-input v-model.trim="queryParams.name" size="small" :minlength="50" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-form-item label="进度" prop="schedule">
        <el-select v-model="queryParams.schedule" size="small" clearable filterable placeholder="请选择进度" style="width: 100%;">
          <el-option
            v-for="item in dict.type.sys_project_schedule"
            :key="+item.value"
            :label="item.label"
            :value="+item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="进度日期" prop="visitDate">
        <el-date-picker
          v-model="projectDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['sa:schedule:query']" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" v-hasPermi="['sa:schedule:query']" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="tableRef"
      :data="tableData"
      v-loading="loading"
      highlight-current-row
      max-height="600"
      v-horizontal-scroll="'auto'"
      style="width: 100%;margin-top: 10px;">
      <el-table-column
        type="index"
        width="50"
        align="center"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="name"
        label="名称"
        align="center"
      />
      <el-table-column
        property="amount"
        label="预算金额(万元)"
        align="center"
      />
      <el-table-column
        property="schedule"
        label="进度"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{ getListValue(scope.row.schedule, dict.type.sys_project_schedule) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        property="nowDate"
        label="进度日期"
        align="center"
      />
      <el-table-column
        property="createBy"
        label="创建人"
        align="center"
      />
      <el-table-column
        property="createTime"
        label="创建时间"
        align="center"
        sortable
      />
      <el-table-column
        label="操作"
        align="center"
        v-if="$auth.hasPermi('sa:schedule:remove')"
      >
        <template slot-scope="scope">
          <el-popconfirm
            confirm-button-text="是"
            cancel-button-text="否"
            title="确定删除吗？"
            @confirm="deleteHandler(scope.row)"
          >
            <el-button slot="reference" icon="el-icon-delete" type="text" v-hasPermi="['sa:schedule:remove']">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :autoScroll="false"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      :title="dialogTitle === 1 ? '增加' : '修改'"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="demo-form">
        <el-form-item label="当前进度日期" prop="nowDate">
          <el-date-picker
            v-model="form.nowDate"
            type="date"
            :picker-options="pickerOptions"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="名称" prop="projectFundId">
          <el-select v-model="form.projectFundId" clearable filterable placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in projectList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进度" prop="schedule">
          <el-select
            v-model="form.schedule"
            filterable
            clearable
            placeholder="请选择进度"
            style="width: 100%;"
          >
            <el-option
              v-for="item in dict.type.sys_project_schedule"
              :key="+item.value"
              :label="item.label"
              :value="+item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="200" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addDataApi, deleteDataApi, getDataListApi, updateDataApi} from "@/api/crm/sa/order";
import { getDataListApi as getAllProjectListApi } from "@/api/crm/md/project";
import {getUserProfile} from "@/api/system/user";

export default {
  name: 'Order',
  dicts: ['sys_project_schedule'],
  data() {
    return {
      currentAmount: 0, // 当前预算金额
      allAmount: 0, // 总预算金额
      // 项目日期
      projectDate: [],
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        createBy: "", // 创建人 *
        createTime: "", // 创建时间 *
        endDate: "", // 结束时间
        id: null, // id
        nowDate: "", // 日期 *
        projectFundId: null, // 项目id *
        projectName: "", // 项目名称
        remark: "", // 备注
        schedule: null, // 进度 *
        startDate: "", // 开始时间
        updateBy: "", // 更新人
        updateTime: "", // 更新时间
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        nowDate: [
          { required: true, message: '请选择日期', trigger: 'blur' }
        ],
        projectFundId: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        schedule: [
          { required: true, message: '请选择进度', trigger: 'change' }
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        isImportant: null, // 是否重点客户 0是普通 1是重点 *
        name: "", // 学校名 *
        province: "", // 省份 *
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 项目数据
      projectList: [],
    }
  },
  watch: {
    projectDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if(newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  created() {
    // this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getAllProjectList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 查询全部项目
    getAllProjectList() {
      getAllProjectListApi().then((res) => {
        this.projectList = res.rows ?? []
      })
    },
    // 选择重点的回调
    changePropertyHandler(val) {
      if(val === 0) {
        this.form.basis = null
      }
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if(+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if(res.code === 200) {
        this.tableData = res.rows
        this.total = res.total

        // this.currentAmount = this.tableData.reduce((acc, cur) => (+acc.amount) + (+cur.amount), 0)
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.form = {...row}
        this.dialogTitle = 2
      } else {
        this.form = { ...this.$options.data().form }
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      this.resetForm('formRef')
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/process/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `projectProcess_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      if(this.form.isImportant === 1 && !(this.form.basis)) {
        this.$notify({
          title: '警告',
          message: '请选择重点依据',
          type: 'warning'
        });
        return false
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
        userId: this.user.userId,
      }
      const res = await addDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if(res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.projectDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>
<style scoped lang="scss">
.grid-content.text{
  margin-top: 10px;
  color: red;
}
</style>
